/**
 * CourseDetailsViewService.java
 * com.sftz.modules.minapp.coursedetails.service
 * Copyright (c) 2018, 北京科技有限公司版权所有.
*/

package com.sftz.modules.minapp.coursedetails.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sftz.assets.entities.CourseCategoryEntity;
import com.sftz.assets.entities.CourseCollectTabEntity;
import com.sftz.assets.entities.CourseCommentTabEntity;
import com.sftz.assets.entities.CourseEntity;
import com.sftz.assets.entities.FabulousTabEntity;
import com.sftz.assets.entities.InstitutionCourseCategoryEntity;
import com.sftz.assets.entities.InstitutionCoursesEntity;
import com.sftz.assets.entities.ResourceDataEntity;
import com.sftz.assets.entities.ResourceEntity;
import com.sftz.assets.entities.SUserEntity;
import com.sftz.assets.entities.TOrderEntity;
import com.sftz.assets.entities.UserCourseStardisEntity;
import com.sftz.assets.entities.UserProductEntity;
import com.sftz.assets.enums.CollecStateEunm;
import com.sftz.assets.enums.CourseResourceTypeEnum;
import com.sftz.assets.enums.DIYResourceTypeEnum;
import com.sftz.assets.enums.DataStatusEnum;
import com.sftz.assets.enums.InsCourseTypeEnum;
import com.sftz.assets.enums.LikeEnum;
import com.sftz.assets.enums.OrderStatusEnum;
import com.sftz.assets.enums.OrderTypeEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.framework.mvc.tag.TimeAgoTag;
import com.sftz.framework.util.CheckTimeUtil;
import com.sftz.modules.minapp.coursedetails.dto.CourseCommentTabDto;
import com.sftz.modules.minapp.coursedetails.dto.CourseDetailsDto;
import com.sftz.modules.minapp.coursedetails.dto.DIYResourceDataDto;
import com.sftz.modules.minapp.coursedetails.dto.ResourceDto;
import com.sftz.modules.minapp.coursedetails.dto.UserCourseRelDto;
import com.sftz.modules.minapp.coursedetails.dto.WebCommentDto;
import com.sftz.modules.minapp.coursedetails.dto.WebCourseTeacherTeamDto;
import com.sftz.modules.minapp.coursedetails.form.CourseDetailsForm;
import com.sftz.modules.minapp.coursedetails.form.WebCourseCommentForm;
import com.sftz.modules.minapp.coursedetailshomework.dto.CourseHomeworkDto;
import com.sftz.modules.minapp.coursedetailshomework.service.CourseHomeworkService;
import com.sftz.modules.minapp.coursedetailstestpaper.dto.TestPaperDto;
import com.sftz.modules.minapp.coursedetailstestpaper.service.TestPaperViewService;
import com.sftz.modules.minapp.coursestudy.dto.CourseLearningRecordDto;
import com.sftz.modules.minapp.coursestudy.form.CourseRecordForm;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.BeanUtil;
import com.uxuexi.core.common.util.DateTimeUtil;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

/**
 * @author   闫志彬
 * @Date	 2018年12月13日 	 
 */
@IocBean
public class CourseDetailsViewService {

	@Inject
	private IDbDao dbDao;

	@Inject
	private SqlManager sqlManager;

	@Inject
	private CourseHomeworkService homeworkService;

	@Inject
	TestPaperViewService testPaperViewService;

	private static final Integer nostar = 0;

	private static final Integer successSta = 1;

	private static final Integer failSta = 2;

	private static final Integer noUser = -1;

	public Object getLearningRecordFirst(CourseRecordForm recordForm) {

		Sql sql = Sqls.create(sqlManager.get("minapp_course_learning_record"));
		sql.setParam("courseId", recordForm.getCourseid());
		String token = recordForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		sql.setParam("userId", userId);
		CourseLearningRecordDto dto = DbSqlUtil.fetchEntity(dbDao, CourseLearningRecordDto.class, sql);
		return dto;

	}

	/**
	 * 查询课程封面
	 */
	public Object getCoursePicture(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		CourseEntity course = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", courseId));
		if (!Util.isEmpty(course)) {
			obj.put("picture", course.getPicture());
		}
		return obj;
	}

	/**
	 * 查询课程信息
	 */
	public Object getCourseInfor(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		//CourseEntity course = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", courseId));
		// 获取课程信息
		CourseDetailsDto course = new CourseDetailsDto();
		Sql courseInfor = Sqls.create(sqlManager.get("minapp_coursedetails_courseInfor"));
		courseInfor.setParam("courseId", courseId);
		course = DbSqlUtil.fetchEntity(dbDao, CourseDetailsDto.class, courseInfor);
		obj.put("course", course);
		// 获取教师简介
		Sql courseTeachTeam = Sqls.create(sqlManager.get("minapp_coursedetails_teacherInfor"));
		courseTeachTeam.setParam("courseId", courseId);
		courseTeachTeam.setParam("showStatus", DataStatusEnum.ENABLE.intKey());
		List<WebCourseTeacherTeamDto> teacherTeam = DbSqlUtil.query(dbDao, WebCourseTeacherTeamDto.class,
				courseTeachTeam);
		for (WebCourseTeacherTeamDto webCourseTeacher : teacherTeam) {
			String teacherIntro = webCourseTeacher.getTeacherIntro();
			if (Util.isEmpty(teacherIntro)) {
				webCourseTeacher.setTeacherIntro("该教师暂未设置简介！");
			}
		}
		obj.put("courseTeachers", teacherTeam);

		//ResourceEntity中存储的类型 ：1为资料包、2为大纲、3为预览视频
		ResourceEntity ResourceEntity = dbDao.fetch(ResourceEntity.class,
				Cnd.where("courseId", "=", courseId).and("resourceType", "=", DIYResourceTypeEnum.OUTLINE.intKey()));
		if (Util.isEmpty(ResourceEntity)) {
			obj.put("outline", "");
		} else {
			ResourceDataEntity resourceDataEntity = dbDao.fetch(ResourceDataEntity.class,
					Cnd.where("resourceId", "=", ResourceEntity.getId()).asc("sort"));
			if (!Util.isEmpty(resourceDataEntity) && !Util.isEmpty(resourceDataEntity.getResourceContent())) {
				obj.put("outline", resourceDataEntity.getResourceContent());
			} else {
				obj.put("outline", "");
			}
		}

		//获取课程评价数据-haozhenbin
		List<WebCommentDto> courseCommentList = courseCommentList(courseId);
		obj.put("courseCommentList", courseCommentList);
		obj.put("courseCommentSize", courseCommentList.size());
		Integer starDisSta = -1;
		//查询当前用户是否已完成星评
		if (!Util.isEmpty(userId)) {
			UserCourseStardisEntity stardis = dbDao.fetch(UserCourseStardisEntity.class,
					Cnd.where("userId", "=", userId).and("courseId", "=", courseId));
			if (Util.isEmpty(stardis)) {
				starDisSta = YesOrNoEnum.YES.intKey();
			} else {
				starDisSta = YesOrNoEnum.NO.intKey();
			}
		}
		obj.put("starDisSta", starDisSta);
		//查询综合评价
		//查询评论总星数
		Sql starAllSql = Sqls.create(sqlManager.get("minapp_coursedetails_course_user_starAll"));
		starAllSql.setParam("courseId", courseId);
		int starAll = DbSqlUtil.fetchInt(dbDao, starAllSql);

		//查询评星总人数
		Sql userAllSql = Sqls.create(sqlManager.get("minapp_coursedetails_course_user_disStartCount"));
		userAllSql.setParam("courseId", courseId);
		int userAll = DbSqlUtil.fetchInt(dbDao, userAllSql);
		Integer avaStar = 0;
		if (starAll != 0 && userAll != 0) {
			BigDecimal decimal1 = new BigDecimal(starAll);
			BigDecimal decimal2 = new BigDecimal(userAll);
			BigDecimal decimal = decimal1.divide(decimal2, 1, RoundingMode.FLOOR);
			avaStar = Math.round(decimal.floatValue());
		}
		obj.put("avaStar", avaStar);

		return obj;
	}

	/**
	 * 查询用户是否购买过该课程决定是否可点击章节列表
	 */
	public Object canClickCourseSturcture(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		if (Util.isEmpty(userId)) {
			throw new IllegalArgumentException("用户id不能为空");
		}
		// 购买的信息
		UserProductEntity userProduct = dbDao.fetch(
				UserProductEntity.class,
				Cnd.where("productId", "=", courseId).and("userId", "=", userId)
						.and("orderType", "=", OrderTypeEnum.COURSE.intKey()));

		//判断 用户有没有购买过 该系列课程
		List<Integer> instCourse = instCourse(courseId);
		boolean asPaySerie = asPaySerie(instCourse, userId);
		if (!Util.isEmpty(userProduct) || asPaySerie) {
			//存在则可点击
			obj.put("canClick", DataStatusEnum.ENABLE.intKey());
		} else {
			//没有则不可点击
			obj.put("canClick", DataStatusEnum.DELETE.intKey());
		}
		return obj;
	}

	/**
	 * 查询课程教师信息
	 */
	public Object getTeacherInfor(CourseDetailsForm courseDetailsForm) {
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		Map<String, Object> obj = new HashMap<String, Object>();
		Sql courseTeachTeam = Sqls.create(sqlManager.get("minapp_coursedetails_teacherInfor"));
		courseTeachTeam.setParam("courseId", courseId);
		courseTeachTeam.setParam("showStatus", DataStatusEnum.ENABLE.intKey());
		List<WebCourseTeacherTeamDto> teacherTeam = DbSqlUtil.query(dbDao, WebCourseTeacherTeamDto.class,
				courseTeachTeam);
		for (WebCourseTeacherTeamDto webCourseTeacher : teacherTeam) {
			String teacherIntro = webCourseTeacher.getTeacherIntro();
			if (Util.isEmpty(teacherIntro)) {
				webCourseTeacher.setTeacherIntro("该教师暂未设置简介！");
			}
		}
		obj.put("courseTeachers", teacherTeam);
		return obj;
	}

	/**
	 * 查询用户对课程报名、收藏、点赞等状态信息
	 */
	public Object getCourseUserInfor(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		if (Util.isEmpty(userId)) {
			throw new IllegalArgumentException("用户id不能为空");
		}
		// 收藏信息
		CourseCollectTabEntity courseCollectTab = new CourseCollectTabEntity();
		courseCollectTab = dbDao.fetch(CourseCollectTabEntity.class,
				Cnd.where("createById", "=", userId).and("collecId", "=", courseId));
		if (!Util.isEmpty(courseCollectTab)) {
			obj.put("collectState", courseCollectTab.getCollecState());
		}
		// 点赞信息
		FabulousTabEntity courseLikeTab = dbDao.fetch(FabulousTabEntity.class,
				Cnd.where("userId", "=", userId).and("courseId", "=", courseId));
		if (!Util.isEmpty(courseLikeTab)) {
			obj.put("likeState", courseLikeTab.getStatus());
		}
		// 购买的信息
		UserProductEntity userProduct = dbDao.fetch(
				UserProductEntity.class,
				Cnd.where("productId", "=", courseId).and("userId", "=", userId)
						.and("orderType", "=", OrderTypeEnum.COURSE.intKey()));
		List<Integer> instCourse = instCourse(courseId);
		//判断 用户有没有购买过 该系列课程
		boolean asPaySerie = asPaySerie(instCourse, userId);
		if (!Util.isEmpty(userProduct) || asPaySerie) {
			//存在则显示立即学习
			obj.put("enrollState", DataStatusEnum.ENABLE.intKey());
		} else {
			//没有则显示立即报名
			obj.put("enrollState", DataStatusEnum.DELETE.intKey());
		}
		// 课程信息
		CourseEntity course = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", courseId));
		obj.put("course", course);
		// 判断课程是不是过期
		Boolean signUpTimeStatus = false;
		InstitutionCoursesEntity institutionCourse = dbDao.fetch(InstitutionCoursesEntity.class,
				Cnd.where("courseId", "=", courseId));
		if (!Util.isEmpty(institutionCourse)) {
			obj.put("courseAttr", institutionCourse.getCourseAttr());

			if (institutionCourse.getCourseAttr() == InsCourseTypeEnum.EDUCATIONINCOURSES.intKey()) {
				//王宏伟：1.判断当前课程报名时间是否过时
				signUpTimeStatus = CheckTimeUtil.belongCalendar(new Date(), institutionCourse.getEnrollStart(),
						institutionCourse.getEnrollEnd());
			}
		}
		obj.put("signUpTimeStatus", signUpTimeStatus);
		return obj;
	}

	/**
	 * 查询课程大纲信息
	 */
	public Object getCourseOutline(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		//ResourceEntity中存储的类型 ：1为资料包、2为大纲、3为预览视频
		ResourceEntity ResourceEntity = dbDao.fetch(ResourceEntity.class,
				Cnd.where("courseId", "=", courseId).and("resourceType", "=", DIYResourceTypeEnum.OUTLINE.intKey()));
		if (Util.isEmpty(ResourceEntity)) {
			obj.put("outline", "");
		} else {
			ResourceDataEntity resourceDataEntity = dbDao.fetch(ResourceDataEntity.class,
					Cnd.where("resourceId", "=", ResourceEntity.getId()).asc("sort"));
			if (!Util.isEmpty(resourceDataEntity) && !Util.isEmpty(resourceDataEntity.getResourceContent())) {
				obj.put("outline", resourceDataEntity.getResourceContent());
			} else {
				obj.put("outline", "");
			}
		}
		return obj;
	}

	/**
	 * 点赞
	 */
	public Object courseLike(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		if (Util.isEmpty(userId)) {
			throw new IllegalArgumentException("用户id不能为空");
		}
		boolean hasLiked = hasLiked(courseId, userId);
		if (hasLiked) {
			//有数据 则判断现在赞的状态
			FabulousTabEntity courseLike = dbDao.fetch(FabulousTabEntity.class, Cnd.where("courseId", "=", courseId)
					.and("userId", "=", userId));
			Integer status = courseLike.getStatus();
			LikeEnum le = EnumUtil.get(LikeEnum.class, status);
			switch (le) {
			case LIKE:
				int update_cancel = dbDao.update(FabulousTabEntity.class,
						Chain.make("status", LikeEnum.CANCELLIKE.intKey()).add("time", DateTimeUtil.nowDateTime()), Cnd
								.where("userId", "=", userId).and("courseId", "=", courseId));
				if (update_cancel >= 1) {
					//取消赞  减一
					if (!Util.isEmpty(courseLike.getId())) {
						Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_likeCountMinusOne"));
						sql.params().set("id", courseId);
						dbDao.execute(sql);
					}
				}
				break;
			case CANCELLIKE:
				int update_like = dbDao.update(FabulousTabEntity.class, Chain.make("status", LikeEnum.LIKE.intKey())
						.add("time", DateTimeUtil.nowDateTime()),
						Cnd.where("userId", "=", userId).and("courseId", "=", courseId));
				if (update_like >= 1) {
					//取消赞  加一
					if (!Util.isEmpty(courseLike.getId())) {
						Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_likeCountAddOne"));
						sql.params().set("id", courseId);
						dbDao.execute(sql);
					}
				}
				break;
			default:
				break;
			}
		} else {
			//没有数据则给粉丝表加一
			FabulousTabEntity fabulousTabEntity = new FabulousTabEntity();
			fabulousTabEntity.setUserId(userId);
			fabulousTabEntity.setCourseId(courseId);
			fabulousTabEntity.setStatus(LikeEnum.LIKE.intKey());
			fabulousTabEntity.setTime(DateTimeUtil.nowDateTime());
			fabulousTabEntity = dbDao.insert(fabulousTabEntity);
			//给课程表数量加一
			Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_likeCountAddOne"));
			sql.params().set("id", courseId);
			dbDao.execute(sql);
		}
		FabulousTabEntity fabulousTab = dbDao.fetch(FabulousTabEntity.class,
				Cnd.where("courseId", "=", courseId).and("userId", "=", userId));
		if (!Util.isEmpty(fabulousTab)) {
			Integer LikeStatus = fabulousTab.getStatus();
			obj.put("likeState", LikeStatus);
		}
		return obj;
	}

	/**
	 * 判断有没有赞过
	 */
	private boolean hasLiked(Integer courseId, Integer userId) {
		if (!Util.isEmpty(userId) && !Util.isEmpty(courseId)) {
			FabulousTabEntity courseLike = dbDao.fetch(FabulousTabEntity.class, Cnd.where("courseId", "=", courseId)
					.and("userId", "=", userId));
			if (!Util.isEmpty(courseLike)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 点收藏
	 */
	public Object courseCollect(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		if (Util.isEmpty(userId)) {
			throw new IllegalArgumentException("用户id不能为空");
		}
		boolean hasCollected = hasCollected(courseId, userId);
		if (hasCollected) {
			//有数据 判断 收藏状态
			CourseCollectTabEntity collectTab = dbDao.fetch(CourseCollectTabEntity.class,
					Cnd.where("createById", "=", userId).and("collecId", "=", courseId).and("collecType", "=", 1));
			Integer collecState = collectTab.getCollecState();
			CollecStateEunm cs = EnumUtil.get(CollecStateEunm.class, collecState);
			switch (cs) {
			case COLLECTYES:
				//已收藏更新为未收藏 修改收藏时间\
				dbDao.update(
						CourseCollectTabEntity.class,
						Chain.make("collecState", CollecStateEunm.COLLECTNO.intKey()).add("collecTime",
								DateTimeUtil.nowDateTime()),
						Cnd.where("createById", "=", userId).and("collecId", "=", courseId).and("collecType", "=", 1));
				break;
			case COLLECTNO:
				//未收藏更新为已收藏 修改收藏时间
				dbDao.update(
						CourseCollectTabEntity.class,
						Chain.make("collecState", CollecStateEunm.COLLECTYES.intKey()).add("collecTime",
								DateTimeUtil.nowDateTime()),
						Cnd.where("createById", "=", userId).and("collecId", "=", courseId));
				break;
			default:
				break;
			}
		} else {
			CourseCollectTabEntity collectTabEntity = new CourseCollectTabEntity();
			collectTabEntity.setCollecId(courseId);
			collectTabEntity.setCollecState(CollecStateEunm.COLLECTYES.intKey());
			collectTabEntity.setCollecType(1);
			collectTabEntity.setCreateById(userId);
			collectTabEntity.setCollecTime(DateTimeUtil.nowDateTime());
			collectTabEntity = dbDao.insert(collectTabEntity);
		}
		CourseCollectTabEntity courseCollectTab = dbDao.fetch(CourseCollectTabEntity.class,
				Cnd.where("collecId", "=", courseId).and("createById", "=", userId).and("collecType", "=", 1));
		if (!Util.isEmpty(courseCollectTab)) {
			Integer collectStatus = courseCollectTab.getCollecState();
			obj.put("collectState", collectStatus);
		}
		return obj;
	}

	/**
	 * 判断有没有收藏过
	 */
	public boolean hasCollected(Integer courseId, Integer userId) {
		if (!Util.isEmpty(userId) && !Util.isEmpty(courseId)) {
			CourseCollectTabEntity collectTab = dbDao.fetch(CourseCollectTabEntity.class,
					Cnd.where("collecId", "=", courseId).and("createById", "=", userId).and("collecType", "=", 1));
			if (!Util.isEmpty(collectTab)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 立即报名
	 */
	public Object courseEnroll(CourseDetailsForm courseDetailsForm) {
		return null;
	}

	/**
	 * 根据课程id 去查询资料包集合
	 */
	public Object findCourseDIYResourceList(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer courseId = courseDetailsForm.getCourseId();
		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}
		//获取课程的详情信息
		CourseEntity courseinfo = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", courseId));
		Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_DIYResourceList"));
		sql.setCondition(Cnd.NEW().and("courseId", "=", courseId)
				.and("resourcetype", "=", DIYResourceTypeEnum.RESOURCE.intKey())
				.and("status", "=", DataStatusEnum.ENABLE.intKey()).asc("sort"));
		List<ResourceDto> diyResourceList = DbSqlUtil.query(dbDao, ResourceDto.class, sql, null);
		// 循环添加集合
		for (int i = 0; i < diyResourceList.size(); i++) {
			List<DIYResourceDataDto> diyResourceDetailsList;
			CourseDetailsForm courseDetailsForm_new = new CourseDetailsForm();
			courseDetailsForm_new.setDiyResourceId(diyResourceList.get(i).getId());
			Map<String, Object> findCourseDIYResourceDetailsList = findCourseDIYResourceDetailsList(courseDetailsForm_new);
			diyResourceDetailsList = (List<DIYResourceDataDto>) findCourseDIYResourceDetailsList
					.get("diyResourceDetailsList");
			diyResourceList.get(i).setDiyResourceDetailsList(diyResourceDetailsList);
		}
		//作业
		List<CourseHomeworkDto> homeWorkInfos = homeworkService.getHomeWorkInfos(courseId, userId);
		//试卷
		List<TestPaperDto> testPaperList = testPaperViewService.testPaperList(courseId, userId);
		obj.put("diyResourceList", diyResourceList);
		obj.put("homeWorkInfos", homeWorkInfos);
		obj.put("testPaperList", testPaperList);
		obj.put("courseinfo", courseinfo);
		return obj;
	}

	/**
	 * 根据DIY资料包id 去查询资料列表
	 */
	public Map<String, Object> findCourseDIYResourceDetailsList(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer diyResourceId = courseDetailsForm.getDiyResourceId();
		if (Util.isEmpty(diyResourceId)) {
			throw new IllegalArgumentException("资料包id不能为空");
		}
		//资料包名称
		ResourceEntity resourceEntity = null;
		resourceEntity = dbDao.fetch(ResourceEntity.class, Cnd.where("id", "=", diyResourceId));
		if (!Util.isEmpty(resourceEntity)) {
			obj.put("resourceName", resourceEntity.getResourceName());
		}
		//资料包下的资源
		Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_DIYResourceDetailsList"));
		sql.params().set("resourceId", diyResourceId);
		List<DIYResourceDataDto> diyResourceDetailsList = DbSqlUtil.query(dbDao, DIYResourceDataDto.class, sql, null);
		obj.put("diyResourceDetailsList", diyResourceDetailsList);
		return obj;
	}

	/**
	 * 根据DIY资料包具体资料id 去查询内容信息
	 */
	public Object findCourseDIYResourceDetailsContent(CourseDetailsForm courseDetailsForm) {
		Map<String, Object> obj = new HashMap<String, Object>();
		Integer diyResourceDetailsId = courseDetailsForm.getResourceId();
		if (Util.isEmpty(diyResourceDetailsId)) {
			throw new IllegalArgumentException("资料id不能为空");
		}
		//资料包名称
		ResourceDataEntity resourceDataEntity = dbDao.fetch(ResourceDataEntity.class,
				Cnd.where("id", "=", diyResourceDetailsId));
		if (!Util.isEmpty(resourceDataEntity)) {
			if (resourceDataEntity.getResourceType() == CourseResourceTypeEnum.DOWNLOAD_TEXT.intKey()) {// 下载资料
				obj.put("detailedInformation", resourceDataEntity.getResourceOriginalUrl());
			} else {
				obj.put("detailedInformation", resourceDataEntity.getResourceContent());
			}
		} else {
			obj.put("detailedInformation", "");
		}
		return obj;
	}

	/**
	 * 查询评价列表-haozhenbin
	 * @param sqlParamForm
	 * @return
	 */
	public List<WebCommentDto> courseCommentList(Integer courseId) {
		Integer nostar = 0;
		Sql sql = Sqls.create(sqlManager.get("minapp_coursedetails_comment_list"));
		sql.params().set("courseId", courseId);
		List<WebCommentDto> lst = DbSqlUtil.query(dbDao, WebCommentDto.class, sql, null);
		for (WebCommentDto webComment : lst) {
			Date commenTime = webComment.getCommenTime();
			String timeFormatText = TimeAgoTag.getTimeFormatText(commenTime);
			if (Util.isEmpty(webComment.getStarDis())) {
				webComment.setStarDis(nostar);
			}
			webComment.setLongTime(timeFormatText);
		}
		return lst;
	}

	public Object saveComment(WebCourseCommentForm sqlParamForm) {

		String token = sqlParamForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		Integer courseId = sqlParamForm.getId();
		//查询当前用户是否报名该课程
		Sql sql = Sqls.create(sqlManager.get("minapp_course_project_count"));
		sql.setParam("userId", userId);
		sql.setParam("courseId", courseId);
		UserCourseRelDto fetchEntity = DbSqlUtil.fetchEntity(dbDao, UserCourseRelDto.class, sql);
		Integer avaStar = 0;
		if (!Util.isEmpty(fetchEntity)) {
			Map<String, Object> obj = Maps.newHashMap();
			Integer res = courseComment(sqlParamForm, fetchEntity);
			List<WebCommentDto> courseCommentList = courseCommentList(courseId);

			//查询当前用户是否已完成星评
			Integer starDisSta = -1;
			UserCourseStardisEntity stardis = dbDao.fetch(UserCourseStardisEntity.class,
					Cnd.where("userId", "=", userId).and("courseId", "=", courseId));

			if (Util.isEmpty(stardis)) {
				starDisSta = YesOrNoEnum.YES.intKey();
			} else {
				starDisSta = YesOrNoEnum.NO.intKey();
			}
			obj.put("starDisSta", starDisSta);
			//查询综合评价
			//查询评论总星数
			Sql starAllSql = Sqls.create(sqlManager.get("minapp_course_user_starAll"));
			starAllSql.setParam("courseId", courseId);
			int starAll = DbSqlUtil.fetchInt(dbDao, starAllSql);

			//查询评星总人数
			Sql userAllSql = Sqls.create(sqlManager.get("minapp_course_user_disStartCount"));
			userAllSql.setParam("courseId", courseId);
			int userAll = DbSqlUtil.fetchInt(dbDao, userAllSql);
			if (starAll != 0 && userAll != 0) {
				BigDecimal decimal1 = new BigDecimal(starAll);
				BigDecimal decimal2 = new BigDecimal(userAll);
				BigDecimal decimal = decimal1.divide(decimal2, 1, RoundingMode.FLOOR);
				avaStar = Math.round(decimal.floatValue());
			}
			obj.put("avaStar", avaStar);
			obj.put("courseComment", res);
			obj.put("courseCommentList", courseCommentList);
			obj.put("courseCommentSize", courseCommentList.size());
			return obj;
		} else {
			return -1;//当前用户未报名该课程
		}
	}

	/**
	 * 操作评论
	 * @param sqlParamForm
	 * @param session
	 * @param fetchEntity
	 * @return
	 */
	public Integer courseComment(final WebCourseCommentForm sqlParamForm, UserCourseRelDto fetchEntity) {
		Integer res;
		CourseCommentTabDto courseCommentTabDto = null;
		if (!Util.isEmpty(sqlParamForm)) {
			try {
				courseCommentTabDto = courseComment(sqlParamForm);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			res = failSta;//评论失败
		}
		if (!Util.isEmpty(courseCommentTabDto)) {
			CourseCommentTabEntity newcourseCommentTabEntity = new CourseCommentTabEntity();
			BeanUtil.copyProperties(courseCommentTabDto, newcourseCommentTabEntity);
			newcourseCommentTabEntity = dbDao.insert(newcourseCommentTabEntity);
			int courseCollectTabId = newcourseCommentTabEntity.getId();
			res = successSta;//评论成功

			//存储相关星评个数
			Integer userId = fetchEntity.getUserId();
			Integer courseId = fetchEntity.getCourseId();
			Integer starDis = sqlParamForm.getStarDis();
			UserCourseStardisEntity stardis = dbDao.fetch(UserCourseStardisEntity.class,
					Cnd.where("userId", "=", userId).and("courseId", "=", courseId));
			if (Util.isEmpty(stardis) && starDis > nostar) {
				UserCourseStardisEntity entity = new UserCourseStardisEntity();
				entity.setUserId(userId);
				entity.setCourseId(courseId);
				entity.setStarDis(starDis);
				dbDao.insert(entity);
			}
		} else {
			res = failSta;//评论失败
		}
		return res;

	}

	public CourseCommentTabDto courseComment(WebCourseCommentForm sqlParamForm) throws ParseException {
		CourseCommentTabDto courseCommentTabDto = new CourseCommentTabDto();
		//根据课程id 查询 创建者id
		CourseEntity courseEntity = null;
		if (!Util.isEmpty(sqlParamForm.getId())) {
			courseEntity = dbDao.fetch(CourseEntity.class, Cnd.where("id", "=", sqlParamForm.getId()));
		}
		String token = sqlParamForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		SUserEntity userNickName = null;
		if (!Util.isEmpty(userId)) {
			userNickName = dbDao.fetch(SUserEntity.class, Cnd.where("id", "=", userId));
		} else {
			return null;
		}
		if (!Util.isEmpty(courseEntity.getId()) && !Util.isEmpty(courseEntity.getCreateBy())) {
			//添加 课程id
			courseCommentTabDto.setCourseId(courseEntity.getId());
			//添加 课程 创建者
			courseCommentTabDto.setCreateById(courseEntity.getCreateBy());
		}
		if (!Util.isEmpty(userId) && !Util.isEmpty(userNickName.getNickName())) {
			//添加 用户id 
			courseCommentTabDto.setCommenUserId(userId);
			//添加 用户 昵称
			courseCommentTabDto.setCommenUserName(userNickName.getNickName());
		}
		if (!Util.isEmpty(sqlParamForm.getCommencontent())) {
			//添加 评论
			courseCommentTabDto.setCommencontent(sqlParamForm.getCommencontent());
		}
		//添加时间
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = dfs.parse(dfs.format(new Date()));
		courseCommentTabDto.setCommenTime(date);
		return courseCommentTabDto;
	}

	public Object evaluateIf(WebCourseCommentForm sqlParamForm) {
		String token = sqlParamForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		Integer courseId = sqlParamForm.getId();

		if (Util.isEmpty(userId)) {
			return noUser;//当前用户未登陆-提示登陆
		} else {
			//查询当前用户是否报名该课程
			Sql sql = Sqls.create(sqlManager.get("minapp_course_project_count"));
			sql.setParam("userId", userId);
			sql.setParam("courseId", courseId);
			UserCourseRelDto fetchEntity = DbSqlUtil.fetchEntity(dbDao, UserCourseRelDto.class, sql);

			if (!Util.isEmpty(fetchEntity)) {
				return successSta;
			} else {
				return failSta;
			}
		}
	}

	/**
	 * 查询当前是否有24小时之内未支付的课程订单
	 */
	public Object findUnpaidCourseInTwentyfourHours(CourseDetailsForm courseDetailsForm) {
		Integer courseId = courseDetailsForm.getCourseId();
		if (Util.isEmpty(courseId)) {
			throw new IllegalArgumentException("参数课程id不能为空");
		}

		String token = courseDetailsForm.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		if (Util.isEmpty(userId)) {
			throw new IllegalArgumentException("用户id不能为空");
		}
		//查询该客户该专业所有订单
		Sql studentS = Sqls.create(sqlManager.get("minapp_coursedetails_24hCanUseOrder"));
		Cnd cnd = Cnd.NEW();
		cnd.and("userId", "=", userId).and("t.orderType", "=", OrderTypeEnum.COURSE.intKey())
				.and("t.productId", "=", courseId).and("t.orderState", "=", OrderStatusEnum.WAIT_PAY.intKey())
				.or("t.orderState", "=", OrderStatusEnum.CANCEL.intKey()).desc("t.orderCreateTime");

		studentS.setCondition(cnd);
		List<TOrderEntity> order = DbSqlUtil.query(dbDao, TOrderEntity.class, studentS);
		TOrderEntity ord = new TOrderEntity();
		//判断24h内未失效的最新订单
		if (!Util.isEmpty(order)) {
			for (TOrderEntity o : order) {
				Date orderCreateTime = o.getOrderCreateTime();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(orderCreateTime);
				calendar.add(calendar.HOUR, 24);
				Date time = calendar.getTime();
				Date dateNow = new Date();
				if (dateNow.before(time)) {
					ord = o;
					break;
				}
			}
		}
		return ord;
	}

	/**
	 * 判断课程是否属于 系列课程
	 * @param courseId
	 * @return 系列课程id
	 */
	private List<Integer> instCourse(Integer courseId) {

		InstitutionCoursesEntity institutionCourses = dbDao.fetch(InstitutionCoursesEntity.class,
				Cnd.where("courseId", "=", courseId));
		if (!Util.isEmpty(institutionCourses)) {
			CourseCategoryEntity courseCategory = dbDao.fetch(CourseCategoryEntity.class,
					Cnd.where("insititutionCourseId", "=", institutionCourses.getId()));
			if (!Util.isEmpty(courseCategory)) {

				List<InstitutionCourseCategoryEntity> list = dbDao.query(InstitutionCourseCategoryEntity.class,
						Cnd.where("id", "=", courseCategory.getClassid()), null);
				List<Integer> lst = Lists.newArrayList();
				for (InstitutionCourseCategoryEntity institutionCourseCategoryEntity : list) {
					lst.add(institutionCourseCategoryEntity.getSeriesId());
				}
				return lst;
			}
		}
		return null;

	}

	/**
	 * 判读用户有没购买过 此课程相关的 系列课程 
	 * @param list
	 * @return 购买过 返回 true
	 */
	private boolean asPaySerie(List<Integer> list, Integer userId) {
		if (!Util.isEmpty(list) && list.size() > 0) {
			List<UserProductEntity> lst = dbDao.query(UserProductEntity.class,
					Cnd.where("productId", "IN", list).and("userId", "=", userId), null);
			if (!Util.isEmpty(lst) && lst.size() > 0) {
				return true;
			}
		}
		return false;
	}
}
